package cn.minsh.lims.eoms.modules.job.task;

import cn.minsh.lims.eoms.common.utils.DateUtils;
import cn.minsh.lims.eoms.modules.app.entity.MaintenancePlanEntity;
import cn.minsh.lims.eoms.modules.app.entity.PlanRemindEntity;
import cn.minsh.lims.eoms.modules.app.enums.BusiTypeEnum;
import cn.minsh.lims.eoms.modules.app.enums.FrequencyEnum;
import cn.minsh.lims.eoms.modules.app.enums.PlanStatusEnum;
import cn.minsh.lims.eoms.modules.app.message.MaintenancePlanRemindMsg;
import cn.minsh.lims.eoms.modules.app.service.MaintenancePlanService;
import cn.minsh.lims.eoms.modules.app.service.PlanRemindService;
import cn.minsh.lims.eoms.modules.app.service.PlanScopeService;
import cn.minsh.lims.eoms.modules.app.service.QueueSendMessageService;
import cn.minsh.lims.eoms.modules.app.utils.LocalDateUtils;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

import static cn.minsh.lims.eoms.modules.app.utils.QueueUtils.INSPECTION_ORDER_REMIND;


/**
 * @author Administrator
 * 保养计划到期，提醒
 */
@Component("checkMaintenancePlanRemindTask")
public class CheckMaintenancePlanRemindTask implements ITask {

    @Autowired
    private MaintenancePlanService maintenancePlanService ;
    @Autowired
    private PlanRemindService planRemindService ;
    @Autowired
    private PlanScopeService planScopeService ;
    @Autowired
    private QueueSendMessageService queueSendMessageService ;

    @Override
    public void run(String params) {

        //读取未开始工单
        List<Integer> statusList = new ArrayList<>() ;
        statusList.add(PlanStatusEnum.NOT_STARTED.getCode()) ;
        statusList.add(PlanStatusEnum.STARTED.getCode()) ;
        QueryWrapper<MaintenancePlanEntity> maintenancePlanEntityQueryWrapper = new QueryWrapper<>() ;
        maintenancePlanEntityQueryWrapper.eq("is_del",0) ;
        maintenancePlanEntityQueryWrapper.in("status",statusList) ;
        List<MaintenancePlanEntity> planList = maintenancePlanService.list(maintenancePlanEntityQueryWrapper) ;

        if (!CollectionUtils.isEmpty(planList)){
            List<Long> planIdList = planList.stream().filter(e->e.getStatus().equals(PlanStatusEnum.NOT_STARTED.getCode())).map(MaintenancePlanEntity::getId).collect(Collectors.toList());

            if (!CollectionUtils.isEmpty(planIdList)) {
                //读取巡检计划所有提醒时间
                QueryWrapper<PlanRemindEntity> wrapper = new QueryWrapper<>();
                wrapper.eq("is_del", 0);
                wrapper.eq("type", BusiTypeEnum.MAINTENANCEPLAN.getCode());
                wrapper.in("plan_id",planIdList) ;
                List<PlanRemindEntity> remindEntityList = planRemindService.list(wrapper);

                if (!CollectionUtils.isEmpty(remindEntityList)){
                    List<MaintenancePlanEntity> updateList = new ArrayList<>() ;
                    List<PlanRemindEntity> finalRemindEntityList = remindEntityList;

                    planList.stream().forEach(e->{
                        //经办人不能为空
                        if (e.getAgentId()==null){return;}

                        if (e.getInvalidTime()!=null && e.getInvalidTime().before(new Date())){
                            e.setStatus(PlanStatusEnum.OVER.getCode());
                            updateList.add(e) ;
                            return;
                        }
                        //计划已开始
                        if (e.getFirstPlanDate().before(new Date())){
                            if (PlanStatusEnum.NOT_STARTED.getCode().equals(e.getStatus())){
                                e.setStatus(PlanStatusEnum.STARTED.getCode());
                                updateList.add(e) ;
                            }
                            Date newPlanDate = null ;
                            //TODO 盘点下一次计划提醒时间，
                            switch (FrequencyEnum.valueOf(e.getFrequency())){
                                case YEAR:
                                    newPlanDate = LocalDateUtils.getNextYear(e.getFirstPlanDate()) ;
                                    break;
                                case MONTH:
                                    newPlanDate = LocalDateUtils.getNextMonth(e.getFirstPlanDate()) ;
                                    break;
                                case WEEK:
                                    newPlanDate = LocalDateUtils.getNextWeek(e.getFirstPlanDate()) ;
                                    break;
                                case DAY:
                                    newPlanDate = new Date() ;
                                    break;
                                default:
                                    break;
                            }
                            if (newPlanDate!=null) {
                                sendMessage(finalRemindEntityList, e, newPlanDate);
                            }
                        }else{
                            sendMessage(finalRemindEntityList,e,e.getFirstPlanDate()) ;
                        }
                    });
                }
            }
        }
    }

    public void sendMessage(List<PlanRemindEntity> remindEntityList,MaintenancePlanEntity e,Date planStartTime){

        if (!CollectionUtils.isEmpty(remindEntityList)) {
            remindEntityList.stream().filter(p -> p.getPlanId().equals(e.getId())).forEach(pp -> {
                if (pp != null) {
                    Date remindDate = LocalDateUtils.addDateDays(planStartTime, -pp.getLeadTime());
                    if (LocalDateUtils.compareDay(remindDate,new Date()) == 0) {
                        //TODO 检查时间，是否到提醒时间了，添加队列
                        /*"标题：保养计划提醒
                        提醒内容：
                        你有一个保养计划需要处理
                        保养计划名称：XXXXXXXX
                        保养时间：XXXXXX"*/
                        MaintenancePlanRemindMsg msg = new MaintenancePlanRemindMsg() ;
                        msg.setTitle("保养计划提醒");
                        msg.setContent("你有一个保养计划需要处理");
                        msg.setPlanName(e.getName());
                        //处理时间
                        msg.setMaintenanceTimes(LocalDateUtils.format(planStartTime, DateUtils.DATE_PATTERN));
                        msg.setReceiver(e.getAgentId()+"");
                        queueSendMessageService.sendMessage(INSPECTION_ORDER_REMIND ,msg);
                        System.out.println(JSONObject.toJSONString(pp));
                    }
                }
            });
        }
    }
}
